package com.qk.exception;


import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常: {}", e);
        return Result.error("服务器发生异常");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        String errMsg = e.getMessage();//获取错误信息
        if (errMsg.contains("Duplicate entry")){//判断是否存在Duplicate entry
            String msg = errMsg.substring(errMsg.indexOf("Duplicate entry"));//截取错误信息substring按照索引截取，indexOf获取索引返回索引
            String[] arr = msg.split(" ");//按空格拆分获取数组
            return Result.error(arr[2] + "已存在");
        }

        return Result.error("服务器发生异常");
    }

    @ExceptionHandler
    public Result handleBusinessException(BusinessException e) {
        return Result.error(e.getMessage());
    }
}
